package com.atguigu.tingshu.common.aspect;


import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.conn.GuiGuLogin;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class GuiGuLoginAspect {

    @Autowired
    private RedisTemplate<String,String > redisTemplate;

    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(annotation)")
    public Object around (ProceedingJoinPoint joinPoint , GuiGuLogin annotation){

        //获取HttpServletRequest对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest httpServletRequest = requestAttributes.getRequest();
        String token = httpServletRequest.getHeader("token");
        // 获取注解对象中的required属性的值，如果是true，就说明当前方法的接口方法是必须要求用户登录的
        if (annotation.required()){
            //判断token是否为空
            if (StringUtils.isEmpty(token)){
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }

            // 如果用户已经进行了登录，就说明token是有值的，根据token从Redis中查询数据
            String  userInfoJson =  redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
            //如果redis中的数据为空,那么抛出异常
            if (StringUtils.isEmpty(userInfoJson)){
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
            // 把用户数据存储到ThreadLocal中
            UserInfo userInfo = JSON.parseObject(userInfoJson, UserInfo.class);
            AuthContextHolder.setUserId(userInfo.getId());
            AuthContextHolder.setUsername(userInfo.getNickname());


        }
        else {
            if (!StringUtils.isEmpty(token)){
                String stringUserInfo = redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
                if (!StringUtils.isEmpty(stringUserInfo)){
                    UserInfo userInfo = JSON.parseObject(stringUserInfo, UserInfo.class);
                    AuthContextHolder.setUserId(userInfo.getId());
                    AuthContextHolder.setUsername(userInfo.getNickname());
                }
            }
        }


        try {
            Object proceed = joinPoint.proceed();

            return proceed;
        } catch (Throwable e) {
            e.printStackTrace();
        }finally{
            AuthContextHolder.removeUserId();
            AuthContextHolder.removeUsername();
        }
        return null;
    }
}
